package com.zkingsoft.wechat;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.httpclient.HttpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.matrix.core.exception.GlobleException;
import com.matrix.core.pojo.AjaxResult;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.matrix.core.web.BaseAction;
import com.zkingsoft.bean.BizCashout;
import com.zkingsoft.bean.BizUser;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.common.constance.AppMessageCode;
import com.zkingsoft.dao.BizBusinessDao;
import com.zkingsoft.dao.BizCashoutDao;
import com.zkingsoft.dao.BizUserDao;
import com.zkingsoft.externalInterface.protocol.payComProtocol.JsApiPayComResData;
import com.zkingsoft.externalInterface.weixinUtil.WeixinServiceUtil;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.service.BizUserService;
import com.zkingsoft.tools.CodeUtil;
import com.zkingsoft.tools.HttpCurlUtil;
import com.zkingsoft.tools.WxUtils;

import net.sf.json.JSONObject;

/**
 * @description (用户表)
 * @author 何明
 * @date 2018-05-23 00:08
 */
@Controller
@RequestMapping(value = "wxapi/user")
public class WxUserAction extends BaseAction {

	@Autowired
	private BizUserService bizUserService;
	
	@Autowired
	private BizBusinessDao bussinesssDao;

	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;
	@Autowired
	private BizUserDao bizUserDao;

	@Autowired
	private BizCashoutDao cashoutDao;

	@Autowired
	private WeixinServiceUtil weixinServiceUtil;

	@Value("${debug}")
	private String isDebug;

	/**
	 * 小程序登录
	 * 
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年5月23日
	 * @param code
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login/{keys}")
	public @ResponseBody AjaxResult wxLogin(@PathVariable("keys") String code) throws Exception {
		AjaxResult res = new AjaxResult();
		if (StringUtils.isNotBlank(code)) {
			String requrl = WeChatApiTools.getXcxLoginUrl(code);
			String reslutData = HttpCurlUtil.sendGetHttp(requrl, null);
			JSONObject json = JSONObject.fromObject(reslutData);
			LogUtil.debug("微信登录获取到登录信息={}", json);
			String openId = json.getString("openid");
			String sessionKey = json.getString("session_key");
			LogUtil.debug("openId={},sessionKey={}", openId, sessionKey);
			// 查询用户是否存在
			BizUser bizUser = bizUserService.findByOpenId(openId);
			if (bizUser == null) {
				// 新增用户
				bizUser = new BizUser();
				bizUser.setSessionKey(sessionKey);
				bizUser.setOpenId(openId);
				bizUser.setLastLoginTime(new Date());
				bizUser.setUserType(AppConstance.USER_TYPE_CUSTOMER);
				bizUser.setQrcode(CodeUtil.encode("{\"userId\":\"" + openId + "\"}", null, true, null));
				bizUserService.add(bizUser);
			} else {
				bizUser.setSessionKey(sessionKey);
				bizUser.setLastLoginTime(new Date());
				// 更新用户sessionKey
				bizUserService.modifyByModel(bizUser);
			}
			// 存放redis
			String token = redisUserLoginUtils.saveUserInfo(bizUser);
			
			
			LogUtil.info("用户token={}", token);

			res.putInMap("token", token);
			
			bizUser=bizUserService.findByOpenId(openId);
			if(bizUser.getStaff()!=null){
				//当前用户是员工账号
				bizUser.setBusiness(bussinesssDao.selectById(bizUser.getStaff().getBusinessId()));
				bizUser.setRole(bizUser.getStaff().getRole());
			}else{
				//当前用户是boss账号
				bizUser.setBusiness(bussinesssDao.findByUserOpenId(bizUser.getOpenId()));
				bizUser.setRole(AppConstance.User_ROLE_BOSS);
			}
			
			res.putInMap("userInfo", bizUser);
			res.setStatus(AjaxResult.STATUS_SUCCESS);

		} else {
			res.setStatus(AjaxResult.STATUS_FAIL);
			res.setInfo("自动登录失败");
		}
		return res;
	}

	/**
	 * 查询用户信息
	 */
	@RequestMapping(value = "/findUserInfo")
	public @ResponseBody AjaxResult findUserInfo() {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		String openId = loginUser.getOpenId();
		BizUser bizUser = bizUserService.findByOpenId(openId);
		
		//处理用户当前所在店铺
		
		if(bizUser.getStaff()!=null){
			//当前用户是员工账号
			bizUser.setBusiness(bussinesssDao.selectById(bizUser.getStaff().getBusinessId()));
			bizUser.setRole(bizUser.getStaff().getRole());
		}else{
			//当前用户是boss账号
			bizUser.setBusiness(bussinesssDao.findByUserOpenId(bizUser.getOpenId()));
			bizUser.setRole(AppConstance.User_ROLE_BOSS);
		}
		
		AjaxResult res = new AjaxResult();
		res.putInMap("userInfo", bizUser);
		res.setStatus(AjaxResult.STATUS_SUCCESS);
		return res;
	}
	
	/**
	 * 获取其他用户简化信息
	 * @author JIANGYOUYAO
	 * @email 935090232@qq.com
	 * @date 2018年9月5日
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "/getOtherUserInfo/{openId}")
	public @ResponseBody AjaxResult getOtherUserInfo(@PathVariable String openId) {
		BizUser bizUser = bizUserService.findByOpenId(openId);
		AjaxResult res = new AjaxResult();
		res.putInMap("userInfo", bizUser);
		res.setStatus(AjaxResult.STATUS_SUCCESS);
		return res;
	}
	

	/**
	 * 接收用户信息
	 */
	@RequestMapping(value = "/saveUserInfo")
	public @ResponseBody AjaxResult saveUserInfo(@RequestBody BizUser bizUser) {

		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		bizUser.setUserId(loginUser.getUserId());
		// TODO 赋值操作
		int i = bizUserService.saveUserInfo(bizUser);

		if (i == 0) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "更新失败");
		}
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, "更新成功");
	}

	/**
	 * 查询资金信息
	 */
	@RequestMapping(value = "/queryAccount")
	public @ResponseBody AjaxResult queryAccount() {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		BizUser bizUser = bizUserDao.selectMoneyById(loginUser.getOpenId());
		LogUtil.debug("资金详情：{}", bizUser);
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, Arrays.asList(bizUser));
	}

	/**
	 * 查询提现记录
	 */
	@RequestMapping(value = "/queryCashOutLog")
	public @ResponseBody AjaxResult queryCashOutLog() {
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		BizCashout cash = new BizCashout();
		cash.setUserId(loginUser.getOpenId());
		List<BizCashout> list = cashoutDao.selectByUserId(loginUser.getOpenId());
		return new AjaxResult(AjaxResult.STATUS_SUCCESS, list, cashoutDao.selectTotalRecord(cash));
	}

	/**
	 * 提现
	 */
	@RequestMapping(value = "/cashOut")
	public @ResponseBody AjaxResult cashOut(@RequestBody BizUser bizUser) {
		if (bizUser == null || bizUser.getCashOutMoney() == null) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "参数错误");
		}
		BizUser loginUser = redisUserLoginUtils.getLoginUser();
		BizCashout cashOut = new BizCashout();
		boolean cashOutFlge = false;

		// 查询用户余额
		BigDecimal userMoney = bizUserDao.selectUserMoney(loginUser.getOpenId());
		if (bizUser.getCashOutMoney().doubleValue() > userMoney.doubleValue()) {
			return new AjaxResult(AjaxResult.STATUS_FAIL, "余额不足");
		}
		// 生成提现记录
		cashOut.setCasId(UUIDUtil.getRandomID());
		cashOut.setCasMoney(bizUser.getCashOutMoney());
		cashOut.setCasType(AppConstance.CAS_TYPE_WXLQ);
		cashOut.setUserId(loginUser.getOpenId());
		cashOut.setCreateBy(loginUser.getOpenId());
		cashOut.setUpdateBy(loginUser.getOpenId());
		cashOut.setCasBatch(WxUtils.getOrderNum());
		cashOut.setCasStatus(AppConstance.CAS_STATUS_TXZ);

		BigDecimal payMoney = bizUser.getCashOutMoney();
		// payMoney = payMoney.multiply(new
		// BigDecimal(AppConstance.ONE_HUNDRED));// 元转换为分
		String payOrderNo = cashOut.getCasBatch();
		String title = "提现";
		if (payMoney.doubleValue() < 10) {
			throw new GlobleException(AppMessageCode.Money.CASHMONET_LIMIT);
		}
		if (payMoney.doubleValue() > (AppConstance.TWENTY_THOUSAND)) {
			throw new GlobleException(AppMessageCode.Money.EXCEEDS_LIMIT);
		}
		payMoney = payMoney.multiply(new BigDecimal(AppConstance.CASHOUT_SCALE));// 扣除2%手续费
		int money = payMoney.multiply(new BigDecimal(AppConstance.ONE_HUNDRED)).intValue();
		// 如果是Debug模式，默认提现1元
		if ("true".equals(isDebug)) {
			money = new BigDecimal(AppConstance.ONE_HUNDRED).intValue();
		}
		try {
			JsApiPayComResData result = weixinServiceUtil.comPay(title, payOrderNo, money, loginUser.getOpenId());
			JSONObject jsonObj = JSONObject.fromObject(result);
			LogUtil.info("#个人提现#付款结果：{}", jsonObj.toString());
			// return_code 和result_code都为SUCCESS
			if (result.getResult_code().equals("SUCCESS")) {
				cashOutFlge = true;
				cashOut.setCasStatus(AppConstance.CAS_STATUS_CG);
				cashOut.setPayBatch(result.getPayment_no());
				cashOut.setReceivedMoney(payMoney);
				LogUtil.debug("扣除前余额:{},扣除金额：{}", userMoney, payMoney);
				userMoney = userMoney.subtract(bizUser.getCashOutMoney());
				// 更新用户余额
				BizUser user = new BizUser();
				user.setUserId(loginUser.getUserId());
				user.setUserMoney(userMoney);
				bizUserDao.updateMoney(user);
			} else {
				// 提现失败，记录失败原因
				cashOut.setCasRemark(result.getErr_code_des());
				cashOut.setCasStatus(AppConstance.CAS_STATUS_SB);
			}
		} catch (Exception e) {
			LogUtil.error("#个人提现异常#{}", e, loginUser.getOpenId());
			cashOut.setCasRemark("提现异常");
			cashOut.setCasStatus(AppConstance.CAS_STATUS_SB);
		}
		// 更新提现信息
		// cashoutDao.updateByModel(cashOut);
		cashoutDao.insert(cashOut);
		if (cashOutFlge) {
			return new AjaxResult(AjaxResult.STATUS_SUCCESS, Arrays.asList(bizUser));
		}
		return new AjaxResult(AjaxResult.STATUS_FAIL, "提现失败");

	}

}